﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ICeFramework.Common.DataLayer;
using System.Data;
using ICeFramework.DataAccess.DataLayer.Enums;

namespace ICeFramework.DataAccess.DataLayer.MsSQL
{
    public class UpdateCommand : DBCommand
    {
        public override DBCommandType CommandType
        {
            get { return DBCommandType.Update; }
        }

        public UpdateCommand(EntityFilter filter, string tableName, IDbTransaction transaction) :
            base(filter, null, tableName, transaction)
        {

        }

        public UpdateCommand(string tableName, IDbTransaction transaction) :
            base(tableName, transaction)
        {

        }

        public override string BuildCommandText(string parameterToken)
        {
            string whereClause = string.Empty;
            string commandText = "UPDATE " + base.EntityName + " SET";
            
            foreach (DataParameter param in Parameters)
            {
                if (param.SourceVersion == DataRowVersion.Current)
                {
                    commandText += " " + param.SourceColumn + " = " + parameterToken + param.ParameterName + ", ";
                }
                else
                {
                    if (param.DbType != DbType.Binary && param.SourceVersion == DataRowVersion.Original)
                    {
                        //daca tipul parametrului este binary nu se pune in conditia de where (image)
                        if (param.IsNullable)
                        {
                            whereClause += "(" + param.SourceColumn + " = " + parameterToken + param.ParameterName
                                + " OR " + param.SourceColumn + " IS NULL AND " + parameterToken + param.ParameterName + " IS NULL) AND ";
                        }
                        else
                        {
                            whereClause += "(" + param.SourceColumn + " = " + parameterToken + param.ParameterName + ") AND ";
                        }
                    }
                }
                if (param.ParameterName.IndexOf(parameterToken) != 0)
                {
                    param.ParameterName = parameterToken + param.ParameterName;
                }
            }

            commandText = commandText.Substring(0, commandText.Length - 2);
            if (!string.IsNullOrEmpty(whereClause))
            {
                whereClause = whereClause.Substring(0, whereClause.Length - 5);
                commandText += " WHERE " + whereClause;
            }

            return commandText;
        }

        public override string BuildPagingCommandText(string parameterToken, int pageIndex, int pageSize)
        {
            throw new NotSupportedException();
        }
    }
}
